# plugs/user.py
#
#

""" user related commands """

__copyright__ = 'this file is in the public domain'

from ommbot.world import add_cmnd, add_example, add_alias, get_users
from ommbot.generic import getwho
users = get_users()

def handle_showuserhosts(bot, ievent):
    ievent.reply("%s %s" % (str(users.userhosts), str(users.masks)))

add_cmnd('user-showuserhosts', handle_showuserhosts, 'OPER')
add_example('user-showuserhosts', 'show usershosts and masks', \
             'user-showuserhosts')

def handle_getuserperm(bot, ievent):
    """ user-allperm <perm> .. list all users with permission <perm> """
    try:
        perm = ievent.args[0].upper()
    except IndexError:
        ievent.missing('<perm>')
        return
    result = []
    for i in users.data:
        if perm in i.perms:
            result.append(i.name)
    if result:
        ievent.reply("users with %s permission: %s" % (perm, \
' .. '.join(result)))
    else:
        ievent.reply("no users with %s permission found" % perm)

add_cmnd('user-allperm', handle_getuserperm, 'OPER')
add_example('user-allperm', 'user-allperm <perm> .. get users with \
             <perm> permission', 'user-allperm rss')

def handle_getuserstatus(bot, ievent):
    """ user-allstatus <status> .. list users with status <status> """
    try:
        status = ievent.args[0].upper()
    except IndexError:
        ievent.missing('<status>')
        return
    result = []
    for i in users.data:
        if status in i.status:
            result.append(i.name)
    if result:
        ievent.reply("users with %s status: %s" % (status, \
' .. '.join(result)))
    else:
        ievent.reply("no users with %s status found" % status)

add_cmnd('user-allstatus', handle_getuserstatus, 'OPER')
add_example('user-allstatus', 'user-allstatus <status> ..get users with \
             <status> status', 'user-allstatus #dunkbots')

def handle_meet(bot, ievent):
    """ meet <nick> .. introduce a new user to the bot """
    try:
        nick = ievent.args[0].lower()
    except IndexError:
        ievent.missing('<nick>')
        return
    if users.exist(nick):
        ievent.reply('there is already a user with username %s' % nick)
        return
    userhost = getwho(bot, nick)
    if not userhost:
        ievent.reply("can't find userhost of %s" % nick)
        return
    username = users.getname(userhost)
    if username:
        ievent.reply('we already have a user with userhost %s (%s)' % \
(userhost, username))
        return
    if users.add(nick, [userhost, ], ['USER', ]):
        ievent.reply('%s added to user database' % nick)

add_cmnd('user-meet', handle_meet, ['OPER', 'MEET'])
add_example('user-meet', 'meet <nick> .. introduce <nick> to the bot', \
            'user-meet dunker')
add_alias('meet', 'user-meet')

def handle_adduser(bot, ievent):
    """ user-add <name> <userhost> .. add a new user to the bot """
    try:
        (name, userhost) = ievent.args
    except ValueError:
        ievent.missing('<name> <userhost>')
        return
    username = users.getname(userhost)
    if username:
        ievent.reply('we already have a user with userhost %s (%s)' % \
(userhost, username))
        return
    if users.add(name.lower(), [userhost, ], ['USER', ]):
        ievent.reply('%s added to user database' % name)

add_cmnd('user-add', handle_adduser, 'OPER')
add_example('user-add', 'user-add <name> <userhost> .. add <name> with \
             <userhost> to the bot', 'user-add dunker bart@localhost')

def handle_merge(bot, ievent):
    """ user-merge <name> <nick> .. merge the userhost into an already \
        existing user """
    if len(ievent.args) != 2:
        ievent.missing('<name> <nick>')
        return  
    name, nick = ievent.args
    if not users.exist(name):
        ievent.reply("we have no user %s" % name)
        return
    userhost = getwho(bot, nick)
    if not userhost:
        ievent.reply("can't find userhost of %s" % nick)
        return
    username = users.getname(userhost)
    if username:
        ievent.reply('we already have a user with userhost %s (%s)' % \
(userhost, username))
        return
    if users.merge(name, userhost):
        ievent.reply('%s merged' % nick)
    else:
        ievent.reply('merge failed')

add_cmnd('user-merge', handle_merge, 'OPER')
add_example('user-merge', 'user-merge <name> <nick> .. merge record with \
             <name> with userhost from <nick>', 'merge bart dunker')
add_alias('merge', 'user-merge')

def handle_delete(bot, ievent):
    """ user-del <name> .. remove user """
    if len(ievent.args) == 0:
        ievent.missing('<name>')
        return
    name = ' ' .join(ievent.args)
    if name == 'owner':
        ievent.reply("can't delete owner")
        return
    users.delete(name)
    ievent.reply('%s deleted' % name)

add_cmnd('user-del', handle_delete, 'OPER')
add_example('user-del', 'user-del <name> .. delete user with <username>' , \
            'user-del dunker')
add_alias('delete', 'user-del')

def handle_us(bot, ievent):
    """ user-scan <txt> .. scan for user """
    try:
        name = ievent.args[0]
    except IndexError:
        ievent.missing('<txt>')
        return
    names = users.names()
    result = []
    for i in names:
        if i.find(name.lower()) != -1:
            result.append(i)
    if result:
        ievent.reply(' .. '.join(result))
    else:
        ievent.reply('no users matched')

add_cmnd('user-scan', handle_us, 'USER')
add_example('user-scan', 'user-scan <txt> .. search database for matching \
             usernames', 'user-scan dunk')
add_alias('us', 'user-scan')

def handle_names(bot, ievent):
    """ user-names .. show registered users """
    ievent.reply(' .. '.join(users.names()))

add_cmnd('user-names', handle_names, 'OPER')
add_example('user-names', 'show names of registered users', 'user-names')
add_alias('names', 'user-names')

def handle_name(bot, ievent):
    """ user-name .. show name of user giving the command """
    ievent.reply('your name is %s' % users.getname(ievent.userhost))

add_cmnd('user-name', handle_name, 'USER')
add_example('user-name', 'show name of user giving the command', 'user-name')
add_alias('name', 'user-name')

def handle_getname(bot, ievent):
    """ user-getname <nick> .. fetch name of nick """
    try:
        nick = ievent.args[0]
    except IndexError:
        ievent.missing("<nick>")
        return
    userhost = getwho(bot, nick)
    if not userhost:
        ievent.reply("can't find userhost of %s" % nick)
        return
    name = users.getname(userhost)
    if not name:
        ievent.reply("can't find user for %s" % userhost)
        return
    ievent.reply(name)

add_cmnd('user-getname', handle_getname, 'USER')
add_example('user-getname', 'user-getname <nick> .. get the name of <nick>', \
            'user-getname dunker')
add_alias('gn', 'user-getname')
add_alias('getname', 'user-getname')

def handle_addperm(bot, ievent):
    """ user-addperm <name> <perm> .. add permission """
    if len(ievent.args) != 2:
        ievent.missing('<name> <perm>')
        return
    (name, perm) = ievent.args
    perm = perm.upper()
    if perm == 'OPER' and not (bot.owner == ievent.userhost):
        ievent.reply('only owner can give oper permission')
        return
    user = users.byname(name)
    if not user:
        ievent.reply("can't find user %s" % name)
        return
    if perm in user.perms:
        ievent.reply('%s already has permission %s' % (name, perm))
        return
    else:
        user.perms.append(perm)
    users.save()
    ievent.reply('%s perm added' % perm)

add_cmnd('user-addperm', handle_addperm, 'OPER')
add_example('user-addperm', 'add permission to user <name>', 'user-addperm \
             dunker rss')
add_alias('setperms', 'user-addperm')
add_alias('addperms', 'user-addperm')

def handle_getperms(bot, ievent):
    """ user-getperms <name> .. get permissions of name"""
    try:
        name = ievent.args[0]
    except IndexError:
        ievent.missing('<name>')
        return
    user = users.byname(name)
    if not user:
        ievent.reply("can't find user %s" % name)
        return
    if user.perms:
        ievent.reply('%s has permissions = %s' % ( name, \
' .. '.join(user.perms)))
    else:
        ievent.reply('%s has no permissions set' % name)

add_cmnd('user-getperms', handle_getperms, 'OPER')
add_example('user-getperms', 'user-getperms <name> .. get permissions of \
             <name>', 'user-getperms dunker')

def handle_perms(bot, ievent):
    """ user-perms .. get permission of the user given the command """
    if ievent.rest:
        ievent.reply('use getperms to get perms of somebody else')
        return
    user = users.getuser(ievent.userhost)
    ievent.reply('%s' % ' .. '.join(user.perms))

add_cmnd('user-perms', handle_perms, 'USER')
add_example('user-perms', 'get permissions', 'user-perms')
add_alias('perms', 'user-perms')

def handle_delperm(bot, ievent):
    """ user-delperm <name> <perm> .. delete permission of name """
    if len(ievent.args) != 2:
        ievent.missing('<name> <perm>')
        return
    name, perm = ievent.args
    perm = perm.upper()
    user = users.byname(name)
    if not user:
        ievent.reply("can't find user %s" % name)
        return
    if perm == 'OPER' and user.name == 'owner':
        ievent.reply("can't delete OPER from owner")
        return 
    if perm in user.perms:
        user.perms.remove(perm)
    else:
        ievent.reply("%s has no %s permission" % (name, perm))
        return
    users.save()
    ievent.reply('%s perm removed' % perm)

add_cmnd('user-delperm', handle_delperm, 'OPER')
add_example('user-delperm', 'user-delperm <name> <perm> .. delete from user \
             <name> permission <perm>', 'user-delperms dunker rss')

def handle_addpermall(bot, ievent):
    """ user-addpermall <perm> .. add permission to all users """
    try:
        perm = ievent.args[0].upper()
    except IndexError:
        ievent.missing('<perm>')
        return
    if perm == 'OPER':
        ievent.reply("can't add OPER permissions to all")
        return
    for i in users.data:
        i.perms.append(perm)
    users.save()
    ievent.reply('%s perm added' % perm)

add_cmnd('user-addpermall', handle_addpermall, 'OPER')
add_example('user-addpermall', 'user-addpermall <perm> .. add <permission> to \
             all users', 'addpermsall USER')

def handle_addstatus(bot, ievent):
    """ user-addstatus <name> <status> .. add status of name """
    if len(ievent.args) != 2:
        ievent.missing('<name> <status>')
        return
    name, status = ievent.args
    status = status.upper()
    user = users.byname(name)
    if not user:
        ievent.reply("can't find user %s" % name)
        return
    if status in user.status:
        ievent.reply("%s already has %s in status list" % \
(name, status))
        return
    user.status.append(status)
    users.save()
    ievent.reply('%s status added' % status)

add_cmnd('user-addstatus', handle_addstatus, 'OPER')
add_example('user-addstatus', 'user-addstatus <name> <status>', \
            'user-addstatus dunker #bartbot')
add_alias('setstatus', 'user-addstatus')
add_alias('addstatus', 'user-addstatus')

def handle_getstatus(bot, ievent):
    """ user-getstatus <name> .. get status of name """
    try:
        name = ievent.args[0]
    except IndexError:
        ievent.missing('<name')
        return
    user = users.byname(name)
    if not user:
        ievent.reply("can't find user %s" % name)
        return
    if user.status:
        ievent.reply('%s has status = %s' % (name, ' .. '.\
join(user.status)))
    else:
        ievent.reply('%s has no status set' % name)

add_cmnd('user-getstatus', handle_getstatus, 'OPER')
add_example('user-getstatus', 'user-getstatus <name> .. get status of \
             <name>', 'user-getstatus dunker')
add_alias('getstatus', 'user-getstatus')

def handle_status(bot, ievent):
    """ user-status .. get status of user given the command """
    user = users.getuser(ievent.userhost)
    if user.status:
        ievent.reply('%s' % ' .. '.join(user.status))
    else:
        ievent.reply('you have no status set')

add_cmnd('user-status', handle_status, 'USER')
add_example('user-status', 'get status', 'user-status')
add_alias('status', 'user-status')

def handle_delstatus(bot, ievent):
    """ user-delstatus <name> <status> .. delete status of name """
    if len(ievent.args) != 2:
        ievent.missing('<name> <status>')
        return
    name, status = ievent.args
    status = status.upper()
    user = users.byname(name)
    if not user:
        ievent.reply("can't find user %s" % name)
        return
    if status in user.status:
        user.status.remove(status)
    else:
        ievent.reply("%s has no %s status" % (name, status))
        return
    users.save()
    ievent.reply('% status deleted' % status)

add_cmnd('user-delstatus', handle_delstatus, 'OPER')
add_example('user-delstatus', 'user-delstatus <name> <status>', \
            'user-delstatus dunker #dunkbots')
add_alias('delstatus', 'user-delstatus')

def handle_adduserhost(bot, ievent):
    """ user-adduserhost <name> <userhost> .. add to userhosts of name """ 
    if bot.owner and ievent.userhost != bot.owner:
        ievent.reply('only owner can use adduserhost')
        return
    if len(ievent.args) != 2:
        ievent.missing('<name> <userhost>')
        return
    name, userhost = ievent.args
    user = users.byname(name)
    if not user:
        ievent.reply("can't find user %s" % name)
        return
    if userhost in user.userhosts:
        ievent.reply("%s already has %s in userhosts list" % \
(name,userhost))
        return
    user.userhosts.append(userhost)
    users.adduserhost(userhost, user)
    users.save()
    ievent.reply('userhost added')

add_cmnd('user-adduserhost', handle_adduserhost, 'OPER')
add_example('user-adduserhost', 'user-adduserhost <name> <userhost> .. add \
             <userhost> to userhosts of <name>', 'user-adduserhost dunker \
             bart?@*.a2000.nl')
add_alias('adduserhost', 'user-adduserhost')
add_alias('adduserhosts', 'user-adduserhost')

def handle_deluserhost(bot, ievent):
    """ user-deluserhost <name> <userhost> .. remove from userhosts of \
        name """
    if bot.owner and ievent.userhost != bot.owner:
        ievent.reply('only owner can use deluserhosts')
        return 
    if len(ievent.args) != 2:
        ievent.missing('<name> <userhost>')
        return
    name, userhost = ievent.args
    user = users.byname(name)
    if not user:
        ievent.reply("can't find user %s" % name)
        return
    if userhost in user.userhosts:
        users.deluserhost(userhost)
        user.userhosts.remove(userhost)
    else:
        ievent.reply("%s has no %s in userhost list" % (name, \
userhost))
        return
    users.save()
    ievent.reply('userhost removed')

add_cmnd('user-deluserhost', handle_deluserhost, 'OPER')
add_example('user-deluserhost', 'user-deluserhost <name> <userhost> .. \
             delete from usershosts of <name> userhost <userhost>', \
             'user-deluserhost dunker bart1@bla.a2000.nl')
add_alias('deluserhost', 'user-deluserhost')
add_alias('deluserhosts', 'user-deluserhost')

def handle_getuserhosts(bot, ievent):
    """ user-getuserhosts <name> .. get userhosts of name """
    try:
        name = ievent.args[0]
    except IndexError:
        ievent.missing('<name>')
        return
    user = users.byname(name)
    if not user:
        ievent.reply("can't find user %s" % name)
        return
    if user.userhosts:
        ievent.reply('%s has userhosts = %s' % (name, ' .. '.join(user\
.userhosts)))
    else:
        ievent.reply('%s has no userhosts set' % name)

add_cmnd('user-getuserhosts', handle_getuserhosts, 'OPER')
add_example('user-getuserhosts', 'user-getuserhosts <name> .. get \
             userhosts of <name>', 'user-getuserhosts dunker')
add_alias('getuserhosts', 'user-getuserhosts')

def handle_userhosts(bot, ievent):
    """ user-userhosts .. get userhosts of user giving the command """
    user = users.getuser(ievent.userhost)
    if user.userhosts:
        ievent.reply('%s' % ' .. '.join(user.\
userhosts))
    else:
        ievent.reply('you have no userhosts set')

add_cmnd('user-userhosts', handle_userhosts, 'USER')
add_example('user-userhosts', 'get userhosts', 'user-userhosts')
add_alias('userhosts', 'user-userhosts')

def handle_setemail(bot, ievent):
    """ user-setemail <emailaddress> .. set email of user giving the \
        command """
    try:
        email = ievent.args[0]
    except IndexError:
        ievent.missing('<email-address>')
        return
    user = users.getuser(ievent.userhost)
    user.email = email
    users.save()
    ievent.reply('email set')

add_cmnd('user-setemail', handle_setemail, 'USER')
add_example('user-setemail', 'user-setemail <emailaddress> .. set email of \
             user that gives the command', 'user-setemail bart@r8.cg.nu')
add_alias('setemail', 'user-setemail')

def handle_getemail(bot, ievent):
    """ user-getemail <name> .. get email of name """
    try:
        name = ievent.args[0]
    except IndexError:
        ievent.missing('<name>')
        return
    user = users.byname(name)
    if not user:
        ievent.reply("can't find user %s" % name)
        return
    if user.email:
        ievent.reply('%s has email %s' % (name, user.email))
    else:
        ievent.reply('%s has no email set' % name)

add_cmnd('user-getemail', handle_getemail, 'USER')
add_example('user-getemail', 'user-getemail <name> .. get email from user \
             <name>', 'user-getemail dunker')
add_alias('getemail', 'user-getemail')

def handle_email(bot, ievent):
    """ user-email .. show email of user giving the command """
    if len(ievent.args) != 0:
        ievent.reply('use getemail to get the email address of an user .. \
email shows your own mail address')
        return
    user = users.getuser(ievent.userhost)
    if user.email:
        ievent.reply('%s' % user.email)
    else:
        ievent.reply('no email set')

add_cmnd('user-email', handle_email, 'USER')
add_example('user-email', 'get email', 'user-email')
add_alias('email', 'user-email')

def handle_delemail(bot, ievent):
    """ user-delemail .. reset email of user giving the command """
    user = users.getuser(ievent.userhost)
    user.email = ""
    users.save()
    ievent.reply('email removed')

add_cmnd('user-delemail', handle_delemail, 'USER')
add_example('user-delemail', 'reset email', 'user-delemail')
add_alias('delemail', 'user-delemail')

def handle_usermatch(bot, ievent):
    """ user-match <userhost> .. show userrecord of user matching userhost """
    try:
        userhost = ievent.args[0]
    except IndexError:
        ievent.missing('<userhost>')
        return
    user = users.getuser(userhost)
    if not user:
        ievent.reply("can't find user for %s" % userhost)
        return
    ievent.reply("userrecord = %s" % str(user))

add_cmnd('user-match', handle_usermatch, ['USER', 'OPER'])
add_example('user-match', 'user-match <userhost>', 'user-match test@test')
add_alias('match', 'user-match')

def handle_usercheck(bot, ievent):
    """ user-check <nick> .. show userrecord of nick """
    try:
        nick = ievent.args[0]
    except IndexError:
        ievent.missing('<nick>')
        return
    userhost = getwho(bot, nick)
    if not userhost:
        ievent.reply("can't find userhost of %s" % nick)
        return
    user = users.getuser(userhost)
    if not user:
        ievent.reply("can't find user for %s" % userhost)
        return
    ievent.reply("userrecord = %s" % str(user))

add_cmnd('user-check', handle_usercheck, 'OPER')
add_example('user-check', 'user-check <nick>', 'user-check dunker')
add_alias('check', 'user-check')

def handle_addpermit(bot, ievent):
    """ user-addpermit <name> <permit> .. add permit to permit list of \
        <name> """
    try:
        who, what = ievent.args
    except:
        ievent.missing("<name> <permit>")
        return
    whouser = users.byname(who)
    if not whouser:
        ievent.reply("can't find username of %s" % who)
        return
    user = users.getuser(ievent.userhost)
    if (who, what) not in user.permit:
        user.permit.append((whouser.name, what))
        users.save()
        ievent.reply('permit added')
    else:
        ievent.reply('%s is already allowed to do %s' % (who, what))

add_cmnd('user-addpermit', handle_addpermit, 'USER')
add_example('user-addpermit', 'user-addpermit <nick> <permit>', \
'user-addpermit dunker todo')
add_alias('addpermit', 'user-addpermit')

def handle_permit(bot, ievent):
    """ user-permit .. get permit list of user giving the command """
    if ievent.rest:
        ievent.reply("use addpermit to allow somebody something .. use \
getname <nick> to get the username of somebody")
        return
    user = users.getuser(ievent.userhost)
    if user.permit:
        ievent.reply("your permit list is %s" % str(user.permit))
    else:
        ievent.reply("you don't have any permits")

add_cmnd('user-permit', handle_permit, 'USER')
add_example('user-permit', 'show permit of user giving the command', \
'user-permit')
add_alias('permit', 'user-permit')

def handle_userdeny(bot, ievent):
    """ user-deny <name> <permit> .. remove (name, permit) from permit list """
    try:
        who, what = ievent.args
    except:
        ievent.missing("<nick> <what>")
        return
    whouser = users.byname(who)
    if not whouser:
        ievent.reply("can't find registered name of %s" % who)
        return
    user = users.getuser(ievent.userhost)
    got = 0
    for i in range(len(user.permit)-1, -1, -1):
        if (whouser.name, what) == user.permit[i]:
            del user.permit[i]
            got = 1
    if got:
        users.save()
        ievent.reply('%s denied' % what)
    else:
        ievent.reply('%s is already not allowed to do %s' % (who, what))

add_cmnd('user-deny', handle_userdeny, 'USER')
add_example('user-deny', 'user-deny <name> <permit>', 'user-deny dunker todo')
add_alias('deny', 'user-deny')
